<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>线路巡检</title>


		<script type="text/javascript" src="https://api.tianditu.gov.cn/api?v=4.0&tk=437c1c53f3848e7d6a3c4c1234e56589">
		</script>
		<script src="js/jquery-3.6.3.min.js"></script>


	<body onLoad="onLoad()" onhashchange="hashchange()">

		<div id="mapDiv">
			<div class="center">
				<input type="button" id="selectit" style="z-index: 999;width: 60px;font-size: 15px;display: none; "
					value="选定" />
			</div>


			<input style="position:fixed ;right: 3vh;top: 20vh;z-index: 999;width: 100px;" type="button" value="添加线路点"
				onclick="togSelect()" />
<!-- 			<input style="position:fixed ;right: 3vh;top: 40vh;z-index: 999;width: 100px;" type="button" value="巡检位置打卡"
				onclick="togSelect()" /> -->
			<img style="position:fixed ;right: 3vh;bottom: 10vh;z-index: 999;width: 50px;" src='https://project.gxrunxiang.com/cdn/location.png' id='img'
				style="width:50px;height: 50px;" />

		</div>

	</body>

</html>
<script type="text/javascript">
	var userAgent = navigator.userAgent;
	if (userAgent.indexOf('AlipayClient') > -1) {
		// 支付宝小程序的 JS-SDK 防止 404 需要动态加载，如果不需要兼容支付宝小程序，则无需引用此 JS 文件。
		document.writeln('<script src="https://appx/web-view.min.js"' + '>' + '<' + '/' + 'script>');
	} else if (/QQ/i.test(userAgent) && /miniProgram/i.test(userAgent)) {
		// QQ 小程序
		document.write(
			'<script type="text/javascript" src="https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"><\/script>'
		);
	} else if (/miniProgram/i.test(userAgent) && /micromessenger/i.test(userAgent)) {
		// 微信小程序 JS-SDK 如果不需要兼容微信小程序，则无需引用此 JS 文件。
		document.write('<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"><\/script>');
	} else if (/toutiaomicroapp/i.test(userAgent)) {
		// 头条小程序 JS-SDK 如果不需要兼容头条小程序，则无需引用此 JS 文件。
		document.write(
			'<script type="text/javascript" src="https://s3.pstatp.com/toutiao/tmajssdk/jssdk-1.0.1.js"><\/script>');
	} else if (/swan/i.test(userAgent)) {
		// 百度小程序 JS-SDK 如果不需要兼容百度小程序，则无需引用此 JS 文件。
		document.write(
			'<script type="text/javascript" src="https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.18.js"><\/script>'
		);
	} else if (/quickapp/i.test(userAgent)) {
		// quickapp
		document.write('<script type="text/javascript" src="https://quickapp/jssdk.webview.min.js"><\/script>');
	}
	// if (!/toutiaomicroapp/i.test(userAgent)) {
	//   document.querySelector('.post-message-section').style.visibility = 'visible';
	// }
</script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js">
	< \/script> <
	script type = "text/javascript"
	src = "https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js" >
</script>
<!-- <script type="text/javascript" src="https://gitee.com/dcloud/uni-app/raw/dev/dist/uni.webview.1.5.4.js"></script> -->

<script>
	// var orignalSetItem = localStorage.setItem;
	// localStorage.setItem = function(key,newValue){
	//     var setItemEvent = new Event("setItemEvent");
	//     setItemEvent.key = key;
	//     setItemEvent.newValue = newValue;
	//     setItemEvent.oldValue = localStorage.getItem(key);
	//     window.dispatchEvent(setItemEvent);
	//     orignalSetItem.apply(this,arguments);
	// }
	// window.addEventListener("setItemEvent", function (e) {
	// 	// console.log("出发了")
	// 	alert('setItemEvent')
	//   //   if (e.key == 'callmsg' && e.newValue!=null) {

	// 		// {   
	// 		// 	window.localStorage.removeItem("callmsg")
	// 		// 	console.log("出发了")
	// 	 //    var arg = 	JSON.parse(localStorage.getItem('callmsg'));
	// 		// eval(e.newValue+"(arg)")

	// 		// }
	//   //   }
	// });
	// window.addEventListener("storage", function (e) {
	// 	alert('storage')
	// });


	var baseUrl = "https://project.gxrunxiang.com/"
	var linedata = {};
	var showselect = false;
	var map;
	var zoom = 12;
	var centermark;
	var mytoken = 'xx';

	document.getElementById('selectit').addEventListener('click', function() {

		var c = map.getCenter()
		var u = `point?latlng=${c.lng},${c.lat}`

		wx.miniProgram.navigateTo({
			url: u
		})
		// uni.postMessage({
		// 	data: {
		// 		action: 'selectit',
		// 		para: map.getCenter()

		// 	}
		// });
		// window.postMessage({
		// 	data:"windowmessage"
		// })
	});
	document.getElementById('img').addEventListener('click', function() {
		// alert('xxxx')
		// calllocate()\
		var u="tianditu"
		wx.miniProgram.navigateTo({
			url: u
		})
		// wx.miniProgram.navigateTo({
		// 	url: 'tianditu'
		// })
		// alert("iping")
  //           var lc = new T.LocalCity();
  //           lc.location(function (e) {
  //               alert(e.cityName);
  //               var marker = new T.Marker(e.lnglat);
		// 		located(e.lnglat.lng,e.e.lnglat.lat)
  //               map.addOverLay(marker);
  //           });

	});


	function hashchange() {
		var hash = this.location.hash.replace('#', "")
		// alert("hash:"+hash)
		if (!hash || hash == '')
			return
	    var allarr = hash.split(";")
		allarr.forEach(e=>{
			// var arr = hash.split('@')
			eval(e)
		})

		// alert(hash)
		// eval("setToken('t')")
		this.location.href = this.location.href.split('#')[0] + "#"

	}

	function setToken(t) {
		this.mytoken = t;
		getdata()
	}

	function showdatas(datas) {
		// view.graphics.removeAll()
		// alert('xxxx')
		// datas = JSON.parse(localStorage.getItem("linedata"))
		// console.log(JSON.stringify(datas))
		// console.log("长度：" + datas.length)
		map.clearOverLays();



		var points = [];
		var lines = {};

		for (var i = 0; i < datas.length; i++) {


			// points.push(this.createpoint(datas[i]))

			map.addOverLay(createpoint(datas[i]));

			if (!lines[datas[i].Name])
				lines[datas[i].Name] = [];
			var lat = datas[i].Latlng.split(',')[0]
			var lng = datas[i].Latlng.split(',')[1]
			lat = parseFloat(lat)
			lng = parseFloat(lng)
			lines[datas[i].Name].push([lng, lat])
		}
		//向地图上添加线
		// map.addOverLay(line);

		// 	if (points.length > 0)
		// 		console.log("view")
		// 	console.log(view)
		// view.graphics.addMany(points)

		for (var i in lines) {
			if (lines[i].length > 1)
				map.addOverLay(createline(lines[i]))
		}

		// this.view.graphics.add(this.createline(lines[i]))

	}

	function createpoint(item) {
		var lat = item.Latlng.split(',')[0]
		var lng = item.Latlng.split(',')[1]
		lat = parseFloat(lat)
		lng = parseFloat(lng)
		const point = {
			type: "point", // autocasts as new Point()
			longitude: lng,
			latitude: lat
		};

		var content = "线路名称:" + item.Name + "</br>铺设类型:" + item.BuildType +
			"</br>序号：" + item.Idx +
			"</br>备注：" + item.Remark + "</br>"
		if (item.ImageList)
			for (var i = 0; i < item.ImageList.length; i++) {
				content +=
					`<img style='width:50px;heigth:50px' src='${baseUrl}/SysFile/download?id=${item.ImageList[i].Id}'/>`
			}
		// content+="<br><a href=''"	
		// console.log("createpoint")
		// console.log(args)
		// console.log(this.gisConstructor)
		// console.log(this.createpoint)
		// var popupTemplate = new PopupTemplate({
		// 	// "title": item.Name,
		// 	"content": content
		// })
		// Create a symbol for drawing the point
		const markerSymbol = {
			type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
			color: [226, 119, 40],
			outline: {
				// autocasts as new SimpleLineSymbol()
				color: [255, 255, 255],
				width: 2
			}
		};

		// Create a graphic and add the geometry and symbol to it
		var marker = new T.Marker(new T.LngLat(lng, lat));
		//向地图上添加标注
		addClickHandler(content, marker);
		return marker
	}

	function createline(linearr) {
		points = [];
		// points.push(new T.LngLat(116.41136, 39.97569));
		linearr.forEach(e => {
			points.push(new T.LngLat(e[0], e[1]));
		})
		var line = new T.Polyline(points, {
			color: "#0000FF",
			weight: 3,
			lineStyle: "solid"
		});

		return line;
	}

	function addClickHandler(content, marker) {
		marker.addEventListener("click", function(e) {
			openInfo(content, e)
		});
	}

	function openInfo(content, e) {
		var point = e.lnglat;
		marker = new T.Marker(point); // 创建标注
		var markerInfoWin = new T.InfoWindow(content, {
			offset: new T.Point(0, -30)
		}); // 创建信息窗口对象
		map.openInfoWindow(markerInfoWin, point); //开启信息窗口
	}

	function calllocate() {
		// alert('xxxxx')
		try {
			wx.getLocation({
				type: 'gcj02', // 默认为wgs84的 gps 坐标，如果要返回直接给 openLocation 用的火星坐标，可传入'gcj02'
				success: function(res) {
					alert(res)
					var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
					var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
					var speed = res.speed; // 速度，以米/每秒计
					var accuracy = res.accuracy; // 位置精度
					alert('xxx')
					located(longitude, latitude)
				},
				fail:function(e)
				{
					alert('errr'+e)
					for(var i in e)
					{
						alert(i+","+e[i])
					}
					console.log(e)
				}
			});
		} catch (e) {
			alert(e)
		}
	}

	function calldata() {
		uni.postMessage({
			data: {
				action: 'calldata',

			}
		});
	}


	function located(lng, lat) {
		// console.log('in located')
		// alert("local,"+t)
		// mytoken=t
		map.centerAndZoom(new T.LngLat(lng, lat), 15);
		// getdata(t)
	}

	function togSelect() {
		this.showselect = !this.showselect
		if (!showselect) {
			document.getElementById("selectit").style.display = "none"
			if (centermark)
				map.removeOverLay(centermark)
			map.removeEventListener("move")
		} else {
			centermark = new T.Marker(map.getCenter()); // 创建标注
			map.addOverLay(centermark); // 将标注添加到地图中
			map.addEventListener("move", e => {
				centermark.setLngLat(map.getCenter())
			})

			document.getElementById("selectit").style.display = ""

		}

	}

	function getdata() {
		var para = {
			Parameters: [],
			orderBys: ["Idx"]
		}
		// alert('开始要数据'+mytoken);
		$.ajax({
			type: "post", // 请求方式
			data: JSON.stringify(para),
			url: `${baseUrl}Line/GetList`, // 请求路径
			dataType: "json", // 预期返回一个 json 类型数据
			beforeSend: (xhr) => {
				// 设置请求头application/json-patch+json
				// alert('beforeSend'+t)
				xhr.setRequestHeader('Authorization', 'Bearer ' + mytoken);
				xhr.setRequestHeader('Content-Type', "application/json-patch+json")
			},
			success: function(res) { // data是形参名，代表返回的数据
				showdatas(res.data)
				// alert(res)
			},
			error: function(e, a) {
				alert("error" + a + e.status + e.readyState)
			}
		});

	}

	function onLoad() {
		// console.log("开始onload")
		// alert(window.localStorage.getItem("callmsg"))
		// console.log('showMap');24.66364876,109.25216533
		map = new T.Map('mapDiv');
		map.centerAndZoom(new T.LngLat(109.25216533, 24.66364876), zoom);



		//创建缩放平移控件对象
		control = new T.Control.Zoom();
		//添加缩放平移控件
		map.addControl(control);
		//创建比例尺控件对象
		var scale = new T.Control.Scale();
		//添加比例尺控件
		map.addControl(scale);
		var copyControl = new T.Control.Copyright({
			position: T_ANCHOR_TOP_LEFT
		});
		map.addControl(copyControl);
		//创建对象

		var typeoption = [{
				title: '地图', //地图控件上所要显示的图层名称
				icon: 'http://api.tianditu.gov.cn/v4.0/image/map/maptype/vector.png', //地图控件上所要显示的图层图标（默认图标大小80x80）
				layer: TMAP_NORMAL_MAP //地图类型对象，即MapType。
			},

			{
				title: '卫星混合',
				icon: 'http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellitepoi.png',
				layer: TMAP_HYBRID_MAP
			},

			{
				title: '地形混合',
				icon: ' http://api.tianditu.gov.cn/v4.0/image/map/maptype/terrainpoi.png',
				layer: TMAP_TERRAIN_HYBRID_MAP
			}
		]
		var ctrl = new T.Control.MapType(typeoption);
		//添加控件
		map.addControl(ctrl);
		newControl = new T.Control({
			position: T_ANCHOR_BOTTOM_RIGHT
		});
		newControl.onAdd = function(map) {
			var container = document.createElement("div");
			var zicsstext =
				"font-size:12px;border:solid 2px blue;background:#fff;padding:2px;line-height:15px;cursor:pointer;";
			var zocsstext =
				"font-size:12px;border:solid 2px blue;background:#fff;padding:2px;line-height:15px;cursor:pointer;";
			this.localButton = createButton("定位", "定位", 'a', container, zicsstext);
			this.localButton.onclick = calllocate;
			return container;
		};
		hashchange()
		// var icon = new T.Icon({
		//     iconUrl: "https://project.gxrunxiang.com/cdn/location.png",
		//     iconSize: new T.Point(19, 27),
		//     iconAnchor: new T.Point(10, 25)
		// });
		// calllocate()
		// getdata()



	}
</script>
</head>
<style>
	html,
	body,
	#mapDiv {
		padding: 0;
		margin: 0;
		height: 100%;
		width: 100%;
	}

	.center {
		/* background: green; */
		position: absolute;
		width: 50px;
		height: 100px;
		left: 50%;
		top: 50%;
		margin-left: -30px;
		margin-top: -75px;
		z-index: 999;
	}
</style>
